package com.che.software.testato.domain.dao.jdbc.impl;

import java.sql.Connection;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import org.apache.commons.dbutils.DbUtils;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Repository;

import com.che.software.testato.domain.dao.IActivityDAO;
import com.che.software.testato.domain.dao.jdbc.adao.AbstractDAO;
import com.che.software.testato.domain.dao.jdbc.exception.ActivityDocumentationCreationDAOException;
import com.che.software.testato.domain.dao.jdbc.exception.ActivitySearchDAOException;
import com.che.software.testato.domain.entity.Activity;
import com.che.software.testato.domain.entity.ActivityAction;
import com.che.software.testato.domain.entity.ActivityParameter;

/**
 * JDBC implementation of the DAO interface dedicated to the activites
 * management.
 * 
 * @author Clement HELIOU (clement.heliou@che-software.com).
 * @copyright Che Software.
 * @license GNU General Public License.
 * @see AbstractDAO, IActivityDAO.
 * @since July, 2011.
 * 
 *        This file is part of Testato.
 * 
 *        Testato is free software: you can redistribute it and/or modify it
 *        under the terms of the GNU General Public License as published by the
 *        Free Software Foundation, either version 3 of the License, or (at your
 *        option) any later version.
 * 
 *        Testato is distributed in the hope that it will be useful, but WITHOUT
 *        ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
 *        FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
 *        for more details.
 * 
 *        You should have received a copy of the GNU General Public License
 *        along with Testato. If not, see <http://www.gnu.org/licenses/>.
 * 
 *        Testato's logo is a creation of Arrioch
 *        (http://arrioch.deviantart.com/) and it's distributed under the terms
 *        of the Creative Commons License.
 */
@Repository("activityDAO")
public class ActivityDAO extends AbstractDAO implements IActivityDAO {

	/**
	 * Constants.
	 */
	private static final Logger LOGGER = Logger.getLogger(ActivityDAO.class);

	/**
	 * Creates the documentation of an activity from actions and parameters
	 * lists.
	 * 
	 * @author Clement HELIOU (clement.heliou@che-software.com).
	 * @param activity the activity to document.
	 * @param actions the actions list.
	 * @param parameters the parameters list.
	 * @since July, 2011.
	 * @throws ActivityDocumentationCreationDAOException if an error occurs
	 *         during the creation.
	 */
	@Override
	public void createActivityDocumentation(Activity activity, List<ActivityAction> actions, List<ActivityParameter> parameters) throws ActivityDocumentationCreationDAOException {
		LOGGER.debug("createActivityDocumentation(" + activity.getActivityId() + "," + actions.size() + " actions," + parameters.size() + " parameters).");
		Connection connection = null;
		try {
			connection = getDataSource().getConnection();
			connection.setAutoCommit(false);
			getQueryRunner().update(connection, "UPDATE activity SET global_description = ? WHERE activity_id = ? ", new Object[] { activity.getGlobalDescription(), activity.getActivityId() });
			int cpt = 1;
			for (ActivityAction action : actions) {
				getQueryRunner().update(connection, "INSERT INTO activity_action(activity_action_id, activity_id, description, result, \"order\") VALUES(nextval('activity_action_id_seq'),?,?,?,?) ", new Object[] { activity.getActivityId(), action.getDescription(), action.getResult(), cpt++ });
			}
			for (ActivityParameter parameter : parameters) {
				getQueryRunner().update(connection, "INSERT INTO activity_parameter(activity_parameter_id, activity_id, name, description) VALUES(nextval('activity_parameter_id_seq'),?,?,?) ", new Object[] { activity.getActivityId(), "{" + parameter.getName() + "}", parameter.getDescription() });
			}
			connection.commit();
		} catch (SQLException e) {
			try {
				connection.rollback();
			} catch (SQLException e1) {
				throw new ActivityDocumentationCreationDAOException(e1);
			}
			throw new ActivityDocumentationCreationDAOException(e);
		} finally {
			if (null != connection) {
				DbUtils.closeQuietly(connection);
			}
		}
	}

	/**
	 * Activities to describe search.
	 * 
	 * @author Clement HELIOU (clement.heliou@che-software.com).
	 * @return the resulting object list.
	 * @since July, 2011.
	 * @throws ActivitySearchDAOException if an error occurs during the search.
	 */
	@Override
	public List<Activity> searchActivitiesToDescribe() throws ActivitySearchDAOException {
		LOGGER.debug("searchActivitiesToDescribe().");
		Connection connection = null;
		try {
			connection = getDataSource().getConnection();
			List<Object> params = new ArrayList<Object>();
			return getQueryRunner().query(connection, getActivitiesToDescribeQuery(null, params), new BeanListHandler<Activity>(Activity.class), params.toArray());
		} catch (SQLException e) {
			throw new ActivitySearchDAOException(e);
		} finally {
			if (null != connection) {
				DbUtils.closeQuietly(connection);
			}
		}
	}

	/**
	 * Activities to describe search from a parent test case id.
	 * 
	 * @author Clement HELIOU (clement.heliou@che-software.com).
	 * @param testCaseId the parent test case id.
	 * @return the resulting object list.
	 * @since July, 2011.
	 * @throws ActivitySearchDAOException
	 */
	@Override
	public List<Activity> searchActivitiesToDescribeFromTestCaseId(int testCaseId) throws ActivitySearchDAOException {
		LOGGER.debug("searchActivitiesToDescribeFromTestCaseId(" + testCaseId + ").");
		Connection connection = null;
		try {
			connection = getDataSource().getConnection();
			List<Object> params = new ArrayList<Object>();
			return getQueryRunner().query(connection, getActivitiesToDescribeQuery(testCaseId, params), new BeanListHandler<Activity>(Activity.class), params.toArray());
		} catch (SQLException e) {
			throw new ActivitySearchDAOException(e);
		} finally {
			if (null != connection) {
				DbUtils.closeQuietly(connection);
			}
		}
	}

	/**
	 * Recovery of the activities to describe query from a test case id that can
	 * be null.
	 * 
	 * @author Clement HELIOU (clement.heliou@che-software.com).
	 * @param testCaseId the optional test case id.
	 * @param params the object array dedicated to the query parameters.
	 * @return the resulting query as a string object.
	 * @since July, 2011.
	 */
	private String getActivitiesToDescribeQuery(Integer testCaseId, List<Object> params) {
		LOGGER.debug("getActivitiesToDescribeQuery().");
		StringBuilder sBuilder = new StringBuilder("SELECT activity_id AS activityId, global_description AS globalDescription, label FROM activity ");
		if (null != testCaseId && 0 != testCaseId) {
			sBuilder.append("JOIN element USING(activity_id) ");
		}
		sBuilder.append("WHERE ");
		if (null != testCaseId && 0 != testCaseId) {
			sBuilder.append("test_case_id = ? AND( ");
			params.add(testCaseId);
		}
		sBuilder.append("global_description IS NULL OR NOT EXISTS( SELECT activity_action_id FROM activity_action WHERE activity_action.activity_id = activity.activity_id ) ");
		if (null != testCaseId && 0 != testCaseId) {
			sBuilder.append(") ");
		}
		sBuilder.append("ORDER BY label ");
		return sBuilder.toString();
	}
}